#ifndef QTPLATFORM_H
#define QTPLATFORM_H

#include <QtGui>
#include <platform.h>
#include <event.h>
#include <renderobject.h>

namespace NITK {

class QtPainter
{
public:
    static QPainter *current() { return inst; }
    static void setCurrent(QPainter *painter) { inst = painter; }
private:
    QtPainter() { assert(0); }
    static QPainter *inst;
};

class QtImageData : public ImageData
{
public:
    QPixmap pixmap;
};

class QtRenderObject;
class GraphicsView : public QGraphicsView
{
    Q_OBJECT
public:
    GraphicsView(Platform *p)
        : QGraphicsView(0, 0), platform(p), bottom(0), right(0)
    {}

    bool event(QEvent *e);
    bool viewportEvent(QEvent *e);

    void itemGeometryChanged(QtRenderObject *object);
private:
    Platform *platform;
    QtRenderObject *bottom, *right;
};
class QtPlatformData : public QObject, public PlatformData
{
    Q_OBJECT
public:
    static QtPlatformData *instance() { return inst; }

    struct Timer {
        Timer() : interval(-1), callback(0) {}
        int interval;
        TimerCallback callback;
    };

    void timerEvent(QTimerEvent *e)
    {
        const Timer &timer = timers.value(e->timerId());
        assert(timer.interval != -1);
        if (timer.callback)
            timer.callback(e->timerId());
    }

    QApplication *application;
    QGraphicsScene *scene;
    GraphicsView *view;

    static QtPlatformData *inst;
    QHash<int, Timer> timers;
};


class QtRenderObject : public QGraphicsRectItem
{
public:
    QtRenderObject(QGraphicsScene *scene, RenderObject *object);
    virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget * = 0);
    void prepareGeometryChange() { QGraphicsItem::prepareGeometryChange(); }
private:
    RenderObject *renderObject;
};

class QtRenderObjectData : public RenderObjectData
{
public:
    QtRenderObjectData(RenderObject *o, int type)
        : RenderObjectData(o, type)
    {
        graphicsItem = new QtRenderObject(QtPlatformData::instance()->scene, o);
    }

    ~QtRenderObjectData()
    {
        delete graphicsItem;
    }

    RenderObject *object;
    QtRenderObject *graphicsItem;
};
};

#endif

